<?php 
	class AdvertModel extends Model {
		const POS_TOP = 0 ;
		const POS_RIGHT = 1 ;
		const POS_LEFT = 2 ;
		const POS_BOTTOM = 3 ;
		public function __construct(){
			$this->open(Model::MYSQL);
			$this->calledClass(get_class($this));
		}
	    public function getAdvertsAndCategorize(){
	    	$this->open(Model::MYSQL);
	    	$query = "SELECT Adverts.*, Galleries.location FROM Adverts, Galleries WHERE Galleries.id = Adverts.img_id ORDER BY Adverts.ad_index ASC ;" ;
	    	$result = $this->query($query);
	    	$rows = array();
	    	while(($row=mysql_fetch_object($result)))$rows[$row->position][]=$row;
	    	return $rows;
	    }
	    /*
	     * Author By Pisey Phon
	    * funtion for count row by position
	    */
	    public function getIndexByPosition($position){
	    	$this->open(Model::MYSQL);
	    	$query = "SELECT ad_index From Adverts WHERE position = $position ;" ;
	    	$result = $this->query($query);
	    	$rows = array();
	    	while(($row=mysql_fetch_object($result)))$rows[]=$row;
	    	return $rows;
	    }
		public function findAsObject($where=array()){
            $this->open(Model::MYSQL);
            $ads = parent::findAsObject($where) ;
           	$query = "SELECT * FROM Galleries WHERE id in ($ads->img_id) ;";
           	$result = $this->query( $query );
           	$rows= array();
           	while(($row=mysql_fetch_object($result)))$rows[]=$row;
			$ads->images = $rows ;
			return $ads;
        }
        public function update($fields=array(),$where=array()){
            $this->open(Model::MYSQL);
            return parent::update($fields,$where);
        }
        public function findObject($fields=array(),$where=array()){
        	$this->open(Model::MYSQL);
        	return parent::findAsObject($fields,$where);
        }
        public function save($fields=array()){
            return parent::save($fields);
        }
        public function delete($ids=array(),$deletestate=array()){
            return parent::delete($ids,true);
        }
		public function getMaxOrder($pos=AdvertModel::POS_TOP){
		  $this->open(Model::MYSQL);
		  $query="SELECT MAX(ad_index) as ad_index FROM Adverts WHERE position=$pos";
		  $result=parent::query($query);
		  $result=mysql_fetch_object($this->query($query));
		  return $result->ad_index;
		}
		public function Indexing($oldIndex,$newIndex,$pos,$aid){
			$this->open(Model::MYSQL);
			$query="SELECT * FROM Adverts WHERE position='$pos' AND ";
			if($oldIndex>$newIndex){
				$query.="ad_index < '$oldIndex' AND ad_index >='$newIndex' ORDER BY ad_index";
				$result = parent::query($query);
				while($row=mysql_fetch_object($result)){
					$this->update(array("ad_index"=>$this->getValue("ad_index",array("id"=>$row->id))+1),array("id="=>$row->id));
				}
			}else{
				$query.="ad_index >'$oldIndex' AND ad_index <= '$newIndex' ORDER BY ad_index";
				$result = parent::query($query);
				while($row=mysql_fetch_object($result)){
					$test[]=$this->update(array("ad_index"=>$this->getValue("ad_index",array("id"=>$row->id))-1),array("id="=>$row->id));
				}
			}
			$this->update(array("ad_index"=>$newIndex),array("id="=>$aid));
		}
		public function getValue($fieldname,$where=array()){
			$this->open(Model::MYSQL);
			if(is_array($where)&&$fieldname!=""){
				foreach ($where AS $field => $value )
					$tmp[] = $field . " = '" . $value . "'" ;
				$query = "SELECT ".$fieldname." FROM Adverts WHERE ".implode(" AND ", $tmp).";" ;
				$record = mysql_fetch_object(parent::query($query));
				return $record->$fieldname;
			}
		}
		/*
		 * Modify by: Ms. Pisey Phon
		 */
		public function getList($page=1,$perpage=20,$search="",$searchFields=array(),$sortFields=array(),$sortCriteria="",$wheres=array()){
			$page=$page<1?1:$page;
			$perpage=$perpage<1?20:$perpage;
			$sortCriteria=$sortCriteria===""?"ASC":$sortCriteria;
			$query = " SELECT Adverts.* FROM Adverts " ;
				
			if(is_array($wheres)&&!empty($wheres)){
				$tempWhereFields=array();
				foreach($wheres AS $field => $val  ){
					if(!empty($val)){
						$tempWhereFields[]= $field ."'".($val)."'"  ;
					}
				}
				if(!empty($tempWhereFields)){
					$query .= " WHERE " . implode(" AND ",$tempWhereFields);
					if(!empty($searchFields)&&(isset($search)&&$search!=="")){
						$tempSearchFields=array();
						foreach($searchFields AS $field ){
							$tempSearchFields[]= " `$field` LIKE '%".($search)."%' " ;
						}
						$query .= " AND ( " . implode(" OR ",$tempSearchFields) . " ) ";
					}
				}else{
					if(!empty($searchFields)&&(isset($search)&&$search!=="")){
						$tempSearchFields=array();
						foreach($searchFields AS $field ){
							$tempSearchFields[]= " `$field` LIKE '%".($search)."%' " ;
						}
						$query .= " WHERE " . implode(" OR ",$tempSearchFields);
					}
				}
			}
			if(!empty($sortFields)){
				$tempSortFields=array();
				foreach($sortFields AS $field ){
					$tempSortFields[]= " `$field` " ;
				}
				$query .= " ORDER BY " . implode(" , ",$tempSortFields) . " " . $sortCriteria . " " ;
			}
			$totalRecords = mysql_num_rows($this->query($query));
			$totalPages = ceil($totalRecords/$perpage);
			$query .= " LIMIT ".(($page-1)*$perpage)." , ".$perpage." ; " ;
			$result = parent::query($query);
			if($result!==null){
				$rows = $result ;
				$result = array();
				while(($row=mysql_fetch_object($rows))!==false){
					$query1="SELECT Galleries.* FROM Galleries WHERE id in ($row->img_id); " ;
					$result1=$this->query($query1);
					while($row1=mysql_fetch_object($result1))$row->img_id=$row1;
					$result[]=$row;
				}
			}
			return array("search"=>$search,"page"=>$page,"perpage"=>$perpage,"totalpages"=>$totalPages,"totalrecords"=>$totalRecords,"records"=>($result===null?array():$result)) ;
		}
		public function getAdsRecord($aid){ 
			$query = "SELECT Adverts.id AS aid,Adverts.position,Adverts.url,Adverts.ad_index,Galleries.id AS gid,Galleries.location FROM Adverts LEFT JOIN Galleries ON Adverts.images=Galleries.id WHERE Adverts.id=$aid";
			$this->open(Model::MYSQL);
			$result = parent::query($query);
			$records = array();
			while($record = mysql_fetch_object($result))$records=$record;
			return $records;
		}
		public function getListOrder($pos=AdvertModel::POS_TOP){
			$query="SELECT ad_index FROM Adverts";
			$this->open(Model::MYSQL);
			$query.=$pos!==""?" WHERE position='".$pos."' ORDER BY ad_index":" ORDER BY ad_index";
			$result = parent::query($query);
			$list = array();
			while($row = mysql_fetch_object($result)) $list[] = $row;
			return $list;
		}
		public function getListPosition(){
			$query="SELECT DISTINCT position FROM Adverts ORDER BY position";
			$this->open(Model::MYSQL);
			$result = parent::query($query);
			$list = array();
			while($record = mysql_fetch_object($result)) $list[] = $record;
			return $list;
		}
		public function getByPosition($pos_id=AdvertModel::POST_TOP){
			$query = "SELECT Adverts.*,Galleries.id AS gid,Galleries.location FROM Adverts LEFT JOIN Galleries ON Adverts.images=Galleries.id WHERE position='".$pos_id."' ORDER BY ad_index";
			$this->open(MODEL::MYSQL);
			$result = parent::query( $query );
			$rows=array();
			while(($row=mysql_fetch_object($result)))$rows[]=$row;
			return $rows;
		}		
		public function getAllLocations(){
			$query = "SELECT position FROM Adverts GROUP BY position " ;
			$this->open(MODEL::MYSQL);
			$result = parent::query( $query );
			$rows=array();
			while(($row=mysql_fetch_assoc($result))){
				$query = "SELECT * FROM Adverts WHERE position = ".$row["position"]." ;" ;
				$sResult = parent::query($query);
				$sRows = array();
				while(($sRow=mysql_fetch_assoc($sResult)))$sRows[]=$sRow;
				$row["childs"]=$sRows;
				$rows[]=$row;
			}
			return $rows;
		}
		public function getByUser($userid){
			$query = "SELECT * FROM Adverts WHERE uid=$userid " ;
			$this->open(MODEL::MYSQL);
			$result = parent::query( $query );
			$rows=array();
			while(($row=mysql_fetch_assoc($result)))$rows[]=$row;
			return $rows;
		}
		public function getByUsers(){
			$query = "SELECT uid FROM Adverts GROUP BY uid " ;
			$this->open(MODEL::MYSQL);
			$result = parent::query( $query );
			$rows=array();
			while(($row=mysql_fetch_assoc($result))){
				$query = "SELECT * FROM Adverts WHERE uid = ".$row["uid"]." ;" ;
				$sResult = parent::query($query);
				$sRows = array();
				while(($sRow=mysql_fetch_assoc($sResult)))$sRows[]=$sRow;
				$row["childs"]=$sRows;
				$rows[]=$row;
			}
			return $rows;
		}
	}